package streamforce.workload.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import streamforce.crypto.message.PolicyMessage;
import streamforce.crypto.owner.EPOwnerClient;

/**
 * Owner to send policy to the cloud
 */
public class PolicySender {
	
	static final Log log = LogFactory.getLog(PolicySender.class); 
	//<streamId> <nPolicies> <startIdx>
	public static void main(String[] args) throws Exception{
		int streamId = new Integer(args[0]).intValue();
		int nPolicies = new Integer(args[1]).intValue();
		int startIdx =  new Integer(args[2]).intValue();		
		
		Properties prop = new Properties();

		prop.load(new FileInputStream("attributes.properties"));			
			    
		int aggType = new Integer(prop.getProperty("aggregateType")).intValue(); 
		
		EPOwnerClient owner = new EPOwnerClient(streamId); 
		for (int i=0; i<nPolicies; i++){
			sendPolicy(owner,streamId,startIdx+i,aggType);
			owner.waitForAck(); 
		}		
		owner.closeConnection(); 
		//owner.waitForAck(); 
	}
	
	private static void sendPolicy(EPOwnerClient owner,int streamId, int policyId, int aggType) throws Exception{		
		//Read from file
		String baseDir = "/DATA/PolicyFiles/policy_";
		String fileName="";
		switch (aggType){
		case -1:
			fileName = baseDir+streamId; 
			break;
		case 1:
			fileName = baseDir+"agg1_"+streamId; 
			break;
		case 2:
			fileName = baseDir+streamId;
			break;
		case 3:
			fileName = baseDir+"agg3_"+streamId; 
			break;
		}		
		ObjectInputStream oi = new ObjectInputStream(new FileInputStream(fileName)); 
		ArrayList<PolicyMessage> policies = (ArrayList<PolicyMessage>)oi.readObject();
		owner.sendPolicy(policies.get(policyId%100)); 
		log.info("SENT POLICY , user id = "
				+ policies.get(policyId%100).getUserIds()[0] + " query = "
				+ policies.get(policyId%100).getQueryExpression()); 
		//owner.sendPolicy(initSimpleClient(owner,streamId,userId));				
	}
}
